var router = require('libs/router').router;
var pages = require('libs/pages');
var ItemMixin = require('mixins/item');
var libs = require('libs/libs');
var api = libs.api;
var expLogin = SA.get('USER');
var store = require('mixins/store')
var pageData = false;
var radio = require('modules/form/radio1')

var Service = require('../_comm/service')

var _page = {
    onlineInfo: false
}

var bindEvent = function(){
    setTimeout(function(){
        // $('#express').find('.flex-1')[0].scrollTop=1000;
        $('#express').find('.flex-1').animate({scrollTop: '1000px'}, 1000)
    },500)
    var getMobijs = SA.get('Mobiscrolljs');
    if (getMobijs && getMobijs ==='finish'){
        dateLib()
    }else{
        SA.set('Mobiscrolljs', dateLib);
    }
    function dateLib(){
        $('#bespeak_treelist').mobiscroll().treelist({
            placeholder: '请选择预约时间',    //input的默认值
            display: 'bottom',               //弹窗的方式
            labels: ['服务器日期','服务器时间'],  // More info about labels: http://docs.mobiscroll.com/2-17-0/list#!opt-labels
            setText: '确定',
            cancelText: '取消'
        });
    }

    //radio
    // var radiodata_express = {
    //     name: ['payWay','payWay'],
    //     title: [<span className="pay_icon_bg"><i className="iconfont icon-weixinzhifu"></i>{'微信支付'}</span>,<span className="pay_icon_bg"><i className="iconfont icon-fukuan"></i>{'货到付款'}</span>],
    //     value: ['-WEIXIN_DBGZH_PAY','PAY_ON_DELIVERY']
    // }

    var radiodata_express = {
        name: ['payWay'],
        title: [<span className="pay_icon_bg"><i className="iconfont icon-weixinzhifu"></i>{'微信支付'}</span>],
        value: ['-WEIXIN_DBGZH_PAY']
    }
    // radio(radiodata_express, 'radiodata_express')
    if ($('#radiodata_express').length){
        radio(radiodata_express, 'radiodata_express')
    }

    if (_page.onlineInfo){
        $('.dCy_branches').css('display','-webkit-box')
    }
    else {
        $('.dCy_branches').css('display','none')
    }

    $(".exp_settlement_no").click(function (){
        ui.alertBox({
            cons: [{text: '暂不提供送货上门', name: "bigCon"}],
            btns: [
                {
                text: '确认',
                close: true
            }]
        })
    })

    $(".exp_settlement").click(function (){ //点击结算 第一个if是没有默认地址，第二个if是没有选择时间
    var _address = $('#express .waterSend_address_address').attr('data-id');
        if(!_address){
            ui.alertBox({
                cons: [{text: '配送地址不能为空', name: "smallCon"}],
                btns: [
                    {
                    text: '确认',
                    close: true
                }]
            })
        }
        else if($("#bespeak_treelist_dummy").val()==''){
            ui.alertBox({
                cons: [{text: '请选择预约时间', name: "smallCon"}],
                btns: [
                    {
                    text: '确认',
                    close: true
                }]
            })
        }
        else{
            var params = {
                login: SA.get('USER').login,
                userName: $('#express .waterSend_address_name').html(),
                bookTimeLine: $("#bespeak_treelist_dummy").val().substring(11),
                bookDate: $("#bespeak_treelist_dummy").val().substring(0,10),
                payCode: $('#radiodata_express input:checked').val(),
                addressId: pageData.address.id,
                method: 'get'
            };
            api.req('/exp_order', params, function(data){
                if(data.code == '100000001'){
                    ui.alertBox({
                       cons: [{text: '订单支付成功', name: "bigCon"}, {text: '等待管家送件上门', name: "smallCon"}],
                       btns: [
                           {
                               text: '查看详情',
                               close: true,
                               callback: function(){
                                   router('expFinish',{back: data.orderId})
                               }
                           }
                       ]
                   })
                   getexpress(true)
                }
                else
                if(data.orderId){
                    if($('#radiodata_express input:checked').val() == 'WEIXIN_DBGZH_PAY'){
                        var _data = JSON.parse(data.orderId);
                        onBridgeReady(_data);
                        function onBridgeReady(datajson){
                            WeixinJSBridge.invoke(
                                'getBrandWCPayRequest', {
                                    "appId" : datajson.appId,     //公众号名称，由商户传入
                                    "timeStamp":datajson.timeStamp,         //时间戳，自1970年以来的秒数
                                    "nonceStr" : datajson.nonceStr, //随机串
                                    "package" : datajson.packageValue,
                                    "signType" : datajson.signType,         //微信签名方式：
                                    "paySign" : datajson.sign //微信签名
                                },
                                function(res){
                                    if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                                        //支付成功后执行
                                        router('expFinish',{back: data.orderId})
                                    }else if(res.err_msg == "get_brand_wcpay_request:cancel" ){
                                        //取消支付，什么都不做
                                    }else if(res.err_msg == "get_brand_wcpay_request:fail" ){
                                        //支付失败
                                        alert(JSON.stringify(res));
                                        alert("支付失败!");
                                    }else{
                                        alert(JSON.stringify(res));
                                    }
                                }
                            )
                        }
                    }
                    // else{            //这个是货到付款的提示框
                    //     ui.alertBox({
                    //         cons: [{text: '下单已成功', name: "bigCon"}, {text: '等待管家送件上门', name: "smallCon"}],
                    //         btns: [
                    //             {
                    //                 text: '查看详情',
                    //                 close: true,
                    //                 callback: function () {
                    //                     router('expFinish',{back: data.orderId})
                    //                 }
                    //             }
                    //         ]
                    //     })
                    // }
                    // fromset
                    getexpress(true)

                }
                else{
                    ui.alertBox({
                        // cons: [{text:'提交失败，请重试',name:"bigCon"}],
                        cons: [{text: data.message, name: "littleCon"}],
                        btns: [
                        ]
                    })
                }
            })
        }
    })

    //点击更换地址
    $('.exp_add').click(function(){
        SA.set('_GoBack', 'express')
        router('uc/addresslist')
    })
    // $('.express').click(function(){
    //     router('express');
    // })
    $('.send').click(function(){
        router('send/send');
    })
    $('.water').click(function(){
        router('water/send');
    })
    $('.waterCard').click(function(){
        router('water/card');
    })
    //短信订阅
    $('.subscribe_btn_express').click(function(){
        router('uc/sms',{'back':'express'});
    });
    //网点介绍
    $('.default_label_branches').click(function(){
        router('uc/siteIntroduce');
    });
    $('.userCenter').click(function(){
        SA.set('_GoBack', 'express')
        router('uc/index',{'back':'express'});
    })
    $('.defult_addrss_selected p').each(function(){
        if($(this).find('span').html() == '请输入收件人姓名' || $(this).find('span').html() == '请输入收件人电话' ){
            $(this).find('span').css('color','#c5c5c5')
        }
    })

    $('.pkgitem').click(function(){
        var pkgid = $(this).attr('data-pkgid');
        var pkgName = $(this).attr('data-name');
        var pkgUrl = $(this).attr('data-url')
        window.location.href = 'http://'+pkgUrl
    })

};
//时间插件所需要的html结构 start
function Waytime(data){
    var abc = []
    if (!data.length){
        return abc
    }
    data.map(function(item, i){
        abc.push(
            <li data-val={item} key={'waytime'+i}>
                {item}
            </li>
        )
    })
    return <ul>{abc}</ul>
}

//end
var Exp = React.createClass({
    mixins: [ItemMixin, store('EXP')],
    componentWillMount: function(){
        if(this.props.data){
            this.setState({
                expressData : this.props.data
            })
        }
        if(this.props.info){
            this.setState({
                expressInfo : this.props.info
            })
        }
    },
    willMount: function(){
        var expressDatas = this.state.expressData
        var expressTime = []
        var expressList = []
        var expressAddress = expressDatas.address || []
        var _totalPriceExpress = 0
        if(expressDatas.pkgList && expressDatas.pkgList.length){
            expressDatas.appointTimes.map(function(item, i){
                var times = Waytime(item.times)
                expressTime.push(
                    <li data-val={item.date} key={'expressTime'+i}>
                        {item.date}
                        {times}
                    </li>
                )
            })
            expressDatas.pkgList.map(function(item, i){
                console.log('========== 包裹');
                console.log(item);
                _totalPriceExpress += item.cost
                expressList.push(
                    <li key={'pkgList' + i} className="pkgitem" data-name={item.expressName} data-pkgid={item.bill} data-val={item.cost} data-url={item.url}><img src={item.imgUrl} alt="" /><span>{item.expressName}-{item.bill}</span></li>
                )
            })
            console.log(_totalPriceExpress);
            return(
                <div className="exp_form">
                    <div className="exp-order box-shadow u-mt-15">
                        <div className="title">代保管快件</div>
                        <ul className="list exp_pack">
                            {expressList}
                        </ul>
                    </div>
                    <div className="default_pd016 mT01 box-shadow exp_add">
                        <div className="defult_addrss_selected">
                            <p><label>姓名</label><span className='waterSend_address_name'>{expressAddress.contact?expressAddress.contact:'请输入收件人姓名'}</span></p>
                            <p><label>电话</label><span className='waterSend_address_phone'>{expressAddress.contactPhone?expressAddress.contactPhone:'请输入收件人电话'}</span></p>
                            <p><label>地址</label><span data-id={expressAddress.id}  className='waterSend_address_address'>{expressAddress.fullAddress?expressAddress.fullAddress:'请选择小区'}</span></p>
                            <i className="iconfont icon-xiangyou"></i>
                        </div>
                    </div>
                    <div className="user_Order">
                        <div data-role="fieldcontain" className="default_pd016 box-shadow u-mt-15 m-form" id="date_treelist">
                            <label>预约时间</label>
                            <ul id="bespeak_treelist" className="u-none">
                                {expressTime}
                            </ul>
                        </div>
                        <div className="default_pay">
                            <div id="radiodata_express" className="pay_radio"></div>
                        </div>
                    </div>
                        {
                            (function(){
                                if (expressDatas.pickup){
                                    return (
                                        <div className="default_foot">
                                            <div className="dF_btn exp_settlement_no dF_btn_big">
                                                <a href="javescript:;" >网点暂不提供送货上门，还得辛苦您来取哦</a>
                                            </div>
                                        </div>
                                    )
                                }
                                else {
                                    return (
                                        <div className="default_foot">
                                            <div className="dF_total">
                                                <p>服务费：<i className="summoney">{'¥ '+_totalPriceExpress}</i></p>
                                            </div>
                                            <div className="dF_btn exp_settlement">
                                                <a href="javescript:;" >提交订单</a>
                                            </div>
                                        </div>
                                    )
                                }
                            })()
                        }
                </div>
            )

        }else{
            return(
                <div className="exp_form">
                    <div className="exp-order box-shadow u-mt-15">
                        <div className="water_no_card">
                            <div className="title">代保管快件</div>
                            <div className="water_no_card_com box-shadow">

                                <i></i><p>您暂无代保管快件</p>
                            </div>
                        </div>
                    </div>
                </div>
            )
        }
    },
    render:function(){
        // var dCydata = this.showonlineWillMount()
        var expressDatehtml = this.willMount()
        var onlineStatus;
        if(!!this.state.expressData.user.isReceiveSms){
            onlineStatus = '短信已订阅'
        }else{
            onlineStatus = '短信订阅'
        }
        return (
            <div className="expressWarp flex flex-v">
                <div className="flex-1 f-oTouch">
                    <div className="nav box-shadow">
                        <div className="express">
                            <a href="javascript:;" className="active">
                                <div className="nav-icon">
                                    <img src="/images/express.png" alt="" />
                                </div>
                                <div className="nav-text"><span>我要收件</span></div>
                            </a>
                        </div>
                        <div className="send">
                            <a href="javascript:;">
                                <div className="nav-icon">
                                    <img src="/images/send.png" alt="" />
                                </div>
                                <div className="nav-text"><span>快递寄件</span></div>
                            </a>
                        </div>
                    </div>
                    <div className="u-mt-15 box-shadow app_index userCenter">
                        <ul className="default_Picture">
                            <li className="uc_coupon">
                                <div>
                                    <img src="/images/icon-user_03.png" alt=""  className="userImg"/>
                                </div>
                                <label className="userTit">个人中心</label>
                                <i className="iconfont icon-xiangyou"></i>
                            </li>
                        </ul>
                    </div>
                    <div className="u-mt-15 default_pd016 default_community box-shadow">
                        <h3>社区便民</h3>
                        <ul>
                            <Service data={this.state.expressInfo}/>
                            <li className="dCy_notice">
                                <div className="dCy_pic">
                                    <img src="/images/img_tu2.png" alt="" />
                                </div>
                                <div className="dCy_b_com">
                                    <div className="dCy_n_com">
                                        <em>小区公告</em>
                                        <p>左邻右里最新动态信息</p>
                                    </div>
                                    <div className="f_submit">
                                        <a className="f_btn subscribe_btn subscribe_btn_express"><i className="iconfont icon-975shoujitongxinlu"></i>{onlineStatus}</a>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                    {expressDatehtml}
                    <div className="u-mb"></div>
                </div>
            </div>
        )
    }
});

function getexpress(fromset){
    var _this = this;
    var express_post = {
        login: SA.get('USER').login,
        method:'get'
    }

    api.req('/onlineInfo',{login: SA.get('USER').login, method:'get'}, function(info){
        if(!info.code){
            _page.onlineInfo = true;
            // SA.setter('ONLINE', {data: data})

            api.req('/orderInfo', express_post, function (data){
                console.log(data);
                if(data.code == '114000' || data.code == '115000'){
                    router('uc/location')
                }else{
                    pageData = data
                    if (fromset){
                        SA.setter('EXP', {expressData: data})
                    }
                    else _this.main(_this, data, info)
                }
            })
        }
    })
}

function start(name){
    return pages.new({
        boot: function(){

        },
        trigger:function(){
            this.libs.changeTitle('服务');    //更改当前页面标题
            // getOnline()
            getexpress.call(this)
        },
        goback: function(){
            router.cb = function(){
                if (wx){
                    wx.closeWindow()
                }
            }
        },
        main: function(self, data, info){
            this.render(
            <Exp itemDefaultMethod={bindEvent} data={data} info={info}/>,
                document.getElementById(name)
            )
        },
        end: function(){
            pageData = false;
            SA.deleter('ONLINE')
            $('.ab_cover,.m-box').remove(); //关闭弹窗
            React.unmountComponentAtNode(document.getElementById(name))
        }
    })
}

module.exports = start;
